<template>
  <el-dialog
    title="基站定位"
    v-model="state.show"
    width="550px"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    append-to-body
    destroy-on-close
  >
    <div id="jzMap" class="mapContainer"></div>
  </el-dialog>
</template>
<script lang="ts" setup>
import AMapLoader from '@amap/amap-jsapi-loader'

const state = reactive({
  show: false,
  row: {} as any,
  lonLat : '',
  //地图对象
  map: null as any,
  //标记对象
  mapMarker:null as any,
  geocoder: null as any,
  autoComplete: null as any,
  // 添加 center 属性
  center: '' 
})

const loadMap = () => {
  (window as any)._AMapSecurityConfig = {
    securityJsCode: '2465f767bead9fe467710aa53a1c6335',
  }
  AMapLoader.load({
    key: '6be4bdf50e7706f9eca082c41941578e', // 申请好的Web端开发者Key，首次调用 load 时必填
    version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: [
      //逆解析插件
      'AMap.Geocoder',
      'AMap.AutoComplete',
    ],
  }).then(() => {
    initMap()
    initGeocoder()
    initAutoComplete()
    if (state.center) {
      regeoCode(state.center)
    }
  })
}

const initMap=()=> {
  state.map = new (window as any).AMap.Map('jzMap', {
    resizeEnable: true,
    zoom: 11, //地图显示的缩放级别
    keyboardEnable: false,
  })
}

const initGeocoder=()=> {
    state.geocoder = new (window as any).AMap.Geocoder({
    city: '010', //城市设为北京，默认：“全国”
    radius: 500, //范围，默认：500
    extensions: 'all'
  })
}

const initAutoComplete=()=> {
  const autoOptions = {
    city: '全国',
  }
  state.autoComplete = new (window as any).AMap.AutoComplete(autoOptions)
}

//添加标记点
const setMarker=(lnglat)=> {
  if (lnglat) {
    state.mapMarker = new (window as any).AMap.Marker({
      // 定义点标记对象
      position: new (window as any).AMap.LngLat(lnglat[0], lnglat[1]),
    })
    state.map.add(state.mapMarker) // 添加点标记在地图上
    state.map.setCenter(lnglat)
    state.map.setZoom(16)
    state.mapMarker.setPosition(lnglat)
  }
}

//经纬度添加标记点
const regeoCode=(lonLat)=>{
  if (lonLat) {
    let lnglat = lonLat.split(',')
    setMarker(lnglat)
  }
}

const openDialog = (row: any) => {
  state.show = true
  state.row = row
  // 提取经纬度
  if (row.latitude && row.longitude) {
    state.center = `${row.longitude},${row.latitude}`
  }
  loadMap()
}

defineExpose({
  openDialog,
})
</script>
<style lang="scss" scoped>
.mapContainer {
  width: 100%;
  height: 240px;
}
</style>